<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>
        .hide {
            display: none;
        }

        .c1 {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, .5);
            z-index: 2;
        }

        .c2 {
            background-color: white;
            position: fixed;
            width: 400px;
            height: 300px;
            top: 50%;
            left: 50%;
            z-index: 3;
            margin-top: -150px;
            margin-left: -200px;
            padding-top: 2%;
            padding-left: 2%;
        }

        .c3 {
            background-color: white;
            position: fixed;
            width: 400px;
            height: 300px;
            top: 50%;
            left: 50%;
            z-index: 3;
            margin-top: -150px;
            margin-left: -200px;
            padding-top: 2%;
            padding-left: 2%;
        }

        #modal p {
            margin-left: 80px;
        }

        input::placeholder {
            color: #D0D0D0;
        }
    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            检测单处理
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <div class='aui-input-row' style='background-color: #addbef !important;width:100%'>
            <div>
                <div class='aui-input-addon' style="text-align: left">物料类别</div>
            </div>
            <div style="font-size: 12px;">
                <input name="operateType" class='aui-radio' type='radio' name='chkResult' value='1' checked>
                <div class='aui-radio-name'>原材料</div>
                <input name="operateType" class='aui-radio' type='radio' name='chkResult' value='2'>
                <div class='aui-radio-name'>辅材料</div>
                <input name="operateType" class='aui-radio' type='radio' name='chkResult' value='3'>
                <div class='aui-radio-name'>外购件</div>
                <input name="operateType" class='aui-radio' type='radio' name='chkResult' value='4'>
                <div class='aui-radio-name'>外协件</div>
            </div>
        </div>
        <div id="citemList" class="aui-content">
            <div class="aui-form" id="citemForm">

            </div>
            <ul class="aui-list aui-form-list">
                <li style='background-color: #addbef !important;width:100%;'>
                    <p style="margin-left:5%;color: #000;font-size: 12px;">外观</p>
                </li>
                <li class="aui-list-item" style='background-color: #addbef !important;width:100%;'>
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label" style="width:100%">抽检数:</div>
                        <div class="aui-list-item-input">
                            <input type="number" id="WGnum" value="" />
                        </div>
                        <div class="aui-list-item-label" style="width:100%">不合格数:</div>
                        <div class="aui-list-item-input">
                            <input type="number" id="WGsum" value="" />
                        </div>
                    </div>
                </li>
                <li style='background-color: #addbef !important;width:100%;'>
                    <p style="margin-left:5%;color: #000;font-size: 12px">色泽</p>
                </li>
                <li class="aui-list-item" style='background-color: #addbef !important;width:100%;''>
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label" style="width:100%">抽检数:</div>
                        <div class="aui-list-item-input" >
                            <input type="number" id="SZnum" value=""  />
                        </div>
                        <div class="aui-list-item-label" style="width:100%">不合格数:</div>
                        <div class="aui-list-item-input" >
                            <input type="number" id="SZsum" value=""  />
                        </div>
                    </div>
                </li>
            </ul>
            <ul class="aui-list aui-form-list">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">缺陷类别</div>
                        <div class="aui-list-item-input">
                            <select id="qualchkitemType">
                            </select>
                        </div>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">缺陷内容</div>
                        <div class="aui-list-item-input"  onclick="goSelectqualchkitem()">
                            <input type="text" disabled="true" placeholder="选择缺陷内容" id="qualchkitem" value=""/>
                        </div>
                        <!-- <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectqualchkitem()"></i> -->
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">备注</div>
                        <div class="aui-list-item-input">
                            <input id="remark"></input>
                        </div>
                    </div>
                </li>
                <div class="aui-content" style="background-color: #ffffff">
                    <ul class="aui-list-view aui-grid-view" id="imgslist">
                        <li class="aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5" id="addpic" onclick="imgClick()">
                            <img class="aui-img-object" src="../image/add.jpg">
                        </li>
                    </ul>
                </div>
            </ul>
        </div>
        
    </div>
    <div class=' aui-btn aui-btn-info aui-btn-block' onclick='Show()'>保存
        </div>
        <div id="shade" class="c1 hide"></div>
        <div id="modal" class="c2 hide">
            <p style="margin-left: 10px;font-size: 1rem;font-weight: 500;color: #212121;text-align: center;">检测结果</p>
            <ul class="aui-list aui-form-list" style="margin-top: 1%;height: 60%;overflow: auto">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">综合判定</div>
                        <div class="aui-list-item-input">
                            <select id="status" onchange="handleChange()">
                            </select>
                        </div>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">批次总数</div>
                        <div class="aui-list-item-input">
                            <input type="number" placeholder="请输入批次总数" id="lotQty" value="" disabled="true" />
                        </div>

                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">总合格数</div>
                        <div class="aui-list-item-input">
                            <input type="number" placeholder="请输入总合格数" id="Qty" value=""
                                onblur="qualifiedQtyChange();" />
                        </div>

                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">总不合格数</div>
                        <div class="aui-list-item-input">
                            <input type="number" placeholder="请输入总不合格数" id="unQty" value="" disabled="true" />
                        </div>
                    </div>
                </li>

            </ul>
            <footer class="aui-bar aui-bar-tab" style="position: absolute;">
                <div class="aui-btn aui-btn-info" style="width:30%;margin-left:2%;" onclick="Hide()">取消</div>
                <div class="aui-btn aui-btn-info" style="width:30%;margin-left:2%;" onclick="doSave()" id="submitButton">确定</div>
            </footer>
        </div>
        <div id="modal2" class="c3 hide">
            <p style="margin-left: 10px;font-size: 1rem;font-weight: 500;color: #212121;text-align: center;">定量检测项</p>
            <ul class="aui-list aui-form-list" id="tbodyHtml" style="margin-top: 1%;height: 60%;overflow: auto;">

            </ul>
            <footer class="aui-bar aui-bar-tab" style="position: absolute;">
                <div class="aui-btn aui-btn-info" style="width:30%;margin-left:2%;" onclick="Hide()">取消</div>
                <div class="aui-btn aui-btn-info" style="width:30%;margin-left:2%;" onclick="addSave()">提交</div>
            </footer>
        </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">
    var chkBillDetailsId = "";
    var chkBillCode = "";
    var josnList = [];

    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;

    var DLnum = "";
    var DLId = "";

    var qualchkitemCode = ""
    var qualchkitemName = ""
    var qualchkitemGid = ""
    //初始化
    apiready = function () {

        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');

        chkBillCode = api.pageParam.chkBillCode
        //查询检测单明细项
        doSearchChkBillDetails()

        //查询业务状态下拉框
        doSearchStatus();

        //查询检测单及物料批次信息
        doSearchChkBillChkResult()

        //查询缺陷下拉框
        doSearchUqcqualchkitem();
        // $("#WGnum").val(1)
        $("#WGsum").val(0)
        // $("#SZnum").val(1)
        //$("#SZsum").val(0)

    };
    function handleChange() {
        var ststus = $("#status").val()
        var lotQty = $("#lotQty").val();
        if (ststus == "2") {
            $("#Qty").val(lotQty)
            $("#unQty").val(0);
        } else if (ststus == "5") {
            $("#Qty").val(0)
            $("#unQty").val(lotQty);
        }
    }
    function Show() {
        //物料类别
        var mrlType = $("input[name='operateType']:checked").val();
        //物料类别非空校验
        if (mrlType == "" || mrlType == null || mrlType == undefined) {
            api.toast({
                msg: '请选择物料类别',
                duration: 3000
            });
            return;
        }
        for (var i = 0; i < list.length; i++) {

            //获取控件类型（0手动输入1多选2单选）
            var controlType = list[i].controlType;
            var itemId = "citem" + i;
            var itemValue = "";

            //手动输入
            if ("0" == list[i].controlType) {
                var minValue = list[i].minValue;
                var maxValue = list[i].maxValue;
                itemValue = document.getElementById(itemId).value;

                //定量判空
               if (itemValue == "" || itemValue == null || itemValue == undefined) {
                    api.toast({
                        msg: '请选择/输入' + list[i].citemName,
                        duration: 3000
                   });
                    return;
                }
                //多选
            } else if ("1" == list[i].controlType) {

                var checkBoxObj = document.getElementsByName(itemId); //这个是以标签的name来取控件
                for (m = 0; m < checkBoxObj.length; m++) {
                    if (checkBoxObj[m].checked) {
                        itemValue = itemValue + checkBoxObj[m].value + ",";
                    }
                }
                if (checkBoxObj.length > 0) {
                    //有选中，则最后一个需要去掉“,”
                    itemValue = itemValue.substring(0, itemValue.length - 1);
                }

                //单选
            } else {
                var radioObj = document.getElementsByName(itemId); //这个是以标签的name来取控件
                for (n = 0; n < radioObj.length; n++) {
                    if (radioObj[n].checked) {
                        itemValue = radioObj[n].value;
                    }
                }
            }
            /* //判空
            if (itemValue == "" || itemValue == null || itemValue == undefined) {
                api.toast({
                    msg: '请选择/输入' + list[i].citemName,
                    duration: 3000
                });
                return;
            } */

            josnList.push({
                "id": list[i].id,
                "chkValue": itemValue
            });
        }

        // console.log(JSON.stringify(josnList));
        //抽检数-外观
        var WGnum = parseInt($("#WGnum").val());
        //不合格数-外观
        var WGsum = parseInt($("#WGsum").val());
        //抽检数-色泽
        var SZnum = parseInt($("#SZnum").val());
        //不合格数-色泽
        var SZsum = parseInt($("#SZsum").val());

        if (isNaN(WGnum)) {
            api.toast({
                msg: '请输入外观抽检数',
                duration: 3000
            });
            return;
        } else {
            if (WGnum < 1) {
                api.toast({
                    msg: '外观抽检数不可以小于1',
                    duration: 3000
                });
                return;
            }
        }

        if (isNaN(WGsum)) {
            api.toast({
                msg: '请输入外观不合格数',
                duration: 3000
            });
            return;
        } else {
            if (WGsum < 0) {
                api.toast({
                    msg: '外观不合格数不允许小于0',
                    duration: 3000
                });
                return;
            }
            if (WGsum > WGnum) {
                api.toast({
                    msg: '外观不合格数不允许大于外观抽检数',
                    duration: 3000
                });
                return;
            }
        }

        if (isNaN(SZnum)) {
            /* api.toast({
                msg: '请输入色泽抽检数',
                duration: 3000
            });
            return; */
        } else {
            if (SZnum < 1) {
                api.toast({
                    msg: '色泽抽检数不可以小于1',
                    duration: 3000
                });
                return;
            }
        }

        if (isNaN(SZsum)) {
            /* api.toast({
                msg: '请输入色泽不合格数',
                duration: 3000
            });
            return; */
        } else {
            if(isNaN(SZnum)){
                api.toast({
                    msg: '请输入色泽抽检数',
                    duration: 3000
                });
                return; 
            }else{
                 if (SZsum < 0) {
                    api.toast({
                        msg: '色泽不合格数不允许小于0',
                        duration: 3000
                    });
                    return;
                }
                if (SZsum > SZnum) {
                    api.toast({
                        msg: '色泽不合格数不允许大于色泽抽检数',
                        duration: 3000
                    });
                    return;
                }
            }
        }

        document.getElementById('modal').classList.remove('hide');
        document.getElementById('shade').classList.remove('hide');
        handleChange()
    }
    function Hide() {
        josnList = []
        document.getElementById('modal').classList.add('hide');
        document.getElementById('shade').classList.add('hide');
        document.getElementById('modal2').classList.add('hide');
    }

    function qualifiedQtyChange() {
        //合格数改变后，修改不合格数量=批次总数-合格数量，允许收货数量=合格数量
        var qualifiedQty = $("#Qty").val();
        var lotQty = $("#lotQty").val();
        var unqualifiedQty = lotQty - qualifiedQty;
        $("#unQty").val(unqualifiedQty);
    }

    //查询检测单明细项
    function doSearchChkBillDetails() {

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getChkBillDetails";
        var data = {
            values: {
                chkBillCode: chkBillCode,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    //会出现多个明细
                    if(list.length > 0){
                        chkBillDetailsId = list[0].chkBillDetailsId
                        getCitemsByDetailId(chkBillDetailsId)
                    }else{
                        api.toast({
                            msg: "检测单不存在检测明细！",
                            duration: 3000
                        });
                    }
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    $api.html($api.byId("divhtml"), "");
                }
            }
        });
    }
    function getCitemsByDetailId(chkBillDetailsId) {
        api.showProgress({
            title: '加载中...',
        });

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getCitemsByDetailIdLLJY";
        var data = {
            values: {
                chkBillDetailsId: chkBillDetailsId,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                api.hideProgress();

                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var chkResult = myobj.chkResult;
                    list = eval(myobj.list);

                    $("#citemForm").children().remove();

                    for (var i = 0; i < list.length; i++) {
                        var controlType = list[i].controlType; //获取控件类型（0手动输入1多选2单选）
                        var citemId = list[i].citemId;
                        var citemCode = list[i].citemCode;
                        var citemName = list[i].citemName;
                        var citemRemark = list[i].citemRemark;

                        var labContent = "";
                        // var labContent = citemCode + "[" + citemName + "]";
                        if (citemRemark != null && citemRemark != "" && citemRemark != undefined) {
                            labContent = citemName + "[" + citemRemark + "]";
                        } else {
                            labContent = citemName;
                        }

                        var itemId = "citem" + i;

                        //定量-手动输入
                        if ("0" == list[i].controlType) {

                            var minValue = list[i].minValue;
                            var maxValue = list[i].maxValue;
                            var standardValue = list[i].standardValue;
                            var chkValue = list[i].chkValue;

                            var valContent = "上限值：" + maxValue + " 下限值：" + minValue  // + " 标准值：" + standardValue;
                            var valContent2 = " 标准值：" + standardValue;

                            var str = "<div class='aui-input-row'>";
                            // str += "<p style='width:" + api.frameWidth + "px ;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align: left;color: #000;'>" + labContent + "</p>";
                            str += "<p style='width:" + api.frameWidth + "px; text-align: left;color: #000; padding-left:10px;'>" + labContent + "</p>";
                            str += "<div>";
                            str += "<div  onclick='chkDialog(\"" + list[i].num + "\",\"" + itemId + "\",\"" + citemName + "\");'>";
                            str += "<input class='aui-input' placeholder='请点击后，输入" + citemName + "' disabled='true'  style='width:50%;font-size:14px;padding-left:10px' id=\"" + itemId + "\"  />";
                            str += "<div  style='text-align: right;color: #d0d0d0;padding-right:5px;font-size:14px;'>";
                            str += "<div>" + valContent + "</div>";
                            str += "<div>" + valContent2 + "</div>";
                            str += "</div>";
                            str += "</div>";
                            str += "</div>";
                            str += "</div>";
                            //手动输入
                            $("#citemForm").append(str);

                            //定性-多选
                        } else if ("1" == list[i].controlType) {

                            //多选（checkbox）
                            var divStr = "<div class='aui-input-row'><p style='width:" + api.frameWidth + "px; text-align:left;color: #000;  padding-left:10px'>" + labContent +
                                "</p><div class='aui-pull-left' >";
                            var citemDs = eval(list[i].citemDs);
                            for (var j = 0; j < citemDs.length; j++) {
                                var citemDId = citemDs[j].id;
                                var citemDCode = citemDs[j].citemDCode;
                                var citemDName = citemDs[j].citemDName;
                                //0待选，1未选，2已选
                                var selectFlag = citemDs[j].selectFlag;
                                //默认选项：1是，2否
                                var isDefault = citemDs[j].isDefault;
                                if (selectFlag == "2") {
                                    divStr = divStr + "<input class='aui-checkbox' type='checkbox' name=\"" + itemId + "\" value=\"" + citemDId + "\" checked><div class='aui-checkbox-name'>" + citemDName + "</div>";
                                } else {
                                    if (isDefault == "1") {
                                        divStr = divStr + "<input class='aui-checkbox' type='checkbox' name=\"" + itemId + "\" value=\"" + citemDId + "\" checked><div class='aui-checkbox-name'>" + citemDName + "</div>";
                                    } else {
                                        divStr = divStr + "<input class='aui-checkbox' type='checkbox' name=\"" + itemId + "\" value=\"" + citemDId + "\" ><div class='aui-checkbox-name'>" + citemDName + "</div>";
                                    }
                                }
                            }

                            $("#citemForm").append(divStr + "</div></div>");

                            //定性-单选
                        } else {

                            //单选（radio）
                            var divStr = "<div class='aui-input-row''><p style='width:" + api.frameWidth + "px; text-align:left;color: #000;  padding-left:10px'>" + labContent +
                                "</p><div class='aui-pull-left' >";
                            var citemDs = eval(list[i].citemDs);
                            for (var j = 0; j < citemDs.length; j++) {
                                var citemDId = citemDs[j].id;
                                var citemDCode = citemDs[j].citemDCode;
                                var citemDName = citemDs[j].citemDName;
                                //0待选，1未选，2已选
                                var selectFlag = citemDs[j].selectFlag;
                                //默认选项：1是，2否
                                var isDefault = citemDs[j].isDefault;
                                if (selectFlag == "2") {
                                    divStr = divStr + "<input class='aui-radio' type='radio' name=\"" + itemId + "\" value=\"" + citemDId + "\" checked><div class='aui-radio-name'>" + citemDName + "</div>";
                                } else {
                                    if (isDefault == "1") {
                                        divStr = divStr + "<input class='aui-radio' type='radio' name=\"" + itemId + "\" value=\"" + citemDId + "\" checked><div class='aui-radio-name'>" + citemDName + "</div>";
                                    } else {
                                        divStr = divStr + "<input class='aui-radio' type='radio' name=\"" + itemId + "\" value=\"" + citemDId + "\"><div class='aui-radio-name'>" + citemDName + "</div>";
                                    }
                                }
                            }

                            $("#citemForm").append(divStr + "</div></div>");
                        }
                    }

                    //失败
                } else {
                    api.hideProgress();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.hideProgress();
                alert(JSON.stringify(err));
            }
        });
    }
    //定性弹窗
    function chkDialog(num, itemId, citemName) {
        document.getElementById('modal2').classList.remove('hide');
        document.getElementById('shade').classList.remove('hide');
        var html = "";
        DLnum = num
        DLId = itemId

        var testitemId = "#" + itemId
        var str = ""
        for (var i = 0; i < num; i++) {
            var itemId2 = "Titem" + i;
            html += "<li class='aui-list-item'>"
            html += "<div class='aui-list-item-inner'>"
            html += "<div class='aui-list-item-label' style='width:80%'>" + citemName + (i + 1) + ':' + "</div>"
            html += "<div class='aui-list-item-input'>"
            html += " <input oninput='if(value.length>10) value=value.slice(0,10)' type='number' placeholder='请输入" + citemName + "' id=\"" + itemId2 + "\"  value=''/>"
            html += "</div>";
            html += "</div>";
            html += "</li>";
            /* html += "<div class='aui-bar aui-bar-tab' style='position: absolute;'></div>"
            html +=  "<div class='aui-btn aui-btn-info' style='width:30%;margin-left:2%;' onclick='Hide()'>取消</div>"
            html +=  "<div class='aui-btn aui-btn-info' style='width:30%;margin-left:2%;'' onclick='addSave()'>提交</div>"
            html += "</div>" */
        }
        $api.html($api.byId("tbodyHtml"), html);

        if ($(testitemId).val() != "") {
            var str = $(testitemId).val()
            var strArr = str.split(",")
            for (var i = 0; i < strArr.length; i++) {
                var itemId2 = "#Titem" + i;
                $(itemId2).val(strArr[i])
            }
        }
    }
    function addSave() {
        var DLtotal = ""
        for (var i = 0; i < DLnum; i++) {
            var itemId = "#Titem" + i;
            if ($(itemId).val() != "") {
                DLtotal = DLtotal + $(itemId).val() + ','
            }
        }
        var testDLId = "#" + DLId
        DLtotal = DLtotal.substring(0, DLtotal.length - 1)
        $(testDLId).val(DLtotal)
        document.getElementById('shade').classList.add('hide');
        document.getElementById('modal2').classList.add('hide');
    }
    //保存
    function doSave() {
        if (!clickThrottle()) return;
        const submitButton = document.getElementById('submitButton');

        submitButton.style.pointerEvents = "none"
        //物料类别
        var mrlType = $("input[name='operateType']:checked").val();


        //抽检数-外观
        var WGnum = $("#WGnum").val();
        //不合格数-外观
        var WGsum = $("#WGsum").val();
        //抽检数-色泽
        var SZnum = $("#SZnum").val();
        //不合格数-色泽
        var SZsum = $("#SZsum").val();
        //不良原因
        var qualchkitem = $("#qualchkitem").val();
        //备注
        var remark = $("#remark").val();

        //业务状态
        var status = $("#status").val();

        //批次总数
        var lotQty = $("#lotQty").val();
        //总合格数
        var Qty = $("#Qty").val();
        //总不合格数
        var unQty = $("#unQty").val();
        if (status == "" || status == null || status == undefined) {
            api.toast({
                msg: '请选择业务状态',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        }
        if (lotQty == "" || lotQty == null || lotQty == undefined) {
            api.toast({
                msg: '请输入批次总数',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        }
        if (Qty == "" || Qty == null || Qty == undefined) {
            api.toast({
                msg: '请输入总合格数',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        } else {
            if (Qty < 0) {
                api.toast({
                    msg: '请输入正确合格数',
                    duration: 3000
                });
                submitButton.style.pointerEvents = "auto"
                return;
            }
            if (Number(lotQty) < Number(Qty)) {
                api.toast({
                    msg: '合格数不允许大于批次总数，请重新输入',
                    duration: 3000
                });
                submitButton.style.pointerEvents = "auto"
                return;
            }
        }
        var lotQtyNew = parseInt(lotQty)
        var qtyNew = parseInt(Qty) + parseInt(unQty)
        if(lotQtyNew!=qtyNew){
            api.toast({
                    msg: '合格数填写异常，请检查！',
                    duration: 3000
                });
                submitButton.style.pointerEvents = "auto"
                return;
        }
        var chkResult = $("#chkResult").val();
        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];
        api.showProgress({
            title: '保存中...',
        });
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names));
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/saveUqcmChkBillDetailLLJY";
        var data = {
            values: {
                mrlType: mrlType,
                chkBillCode: chkBillCode, //检测单号
                josnList: JSON.stringify(josnList),
                WGnum: WGnum,
                WGsum: WGsum,
                SZnum: SZnum,
                SZsum: SZsum,
                qualchkitem: qualchkitemCode,
                remark: remark,
                status: status,
                lotQty: lotQty,
                Qty: Qty,
                unQty: unQty,
                un: un,
                chkResult: chkResult,
                picNames: picNames,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    api.hideProgress();
                    submitButton.style.pointerEvents = "auto"
                    api.toast({
                        msg: "来料检验保存成功！",
                        duration: 3000
                    });
                    // //返回主界面，刷新表格数据
                    api.closeWin();
                    var name = api.pageParam.name;
                    api.execScript({
                        name: name,
                        script: 'reset()'
                    });
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    api.hideProgress();
                    submitButton.style.pointerEvents = "auto"
                }
            } else {
                api.hideProgress();
                submitButton.style.pointerEvents = "auto"
                alert(JSON.stringify(err));
            }
        });


    }
    //查询检测单及物料批次信息
    function doSearchChkBillChkResult() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getChkBillChkResult";

        var data = {
            values: {
                chkBillCode: chkBillCode,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var chkBill = eval(myobj.chkBill);
                    //var chkResult = chkBill.chkResult;//检测结果
                    var lotQty = chkBill.lotQty;//批次总数
                    var qualifiedQty = chkBill.qualifiedQty;//合格数量
                    var unqualifiedQty = chkBill.unqualifiedQty;//不合格数量
                    //var allowedReceiveQty=chkBill.allowedReceiveQty;//允许收货数量
                    var status = chkBill.status;//业务状态
                    var mrlRemark = chkBill.mrlRemark;//备注
                    var qualchkitem = chkBill.qualchkitemName;//缺陷
                    //$("#chkResult").val(chkResult);
                    $("#lotQty").val(lotQty);
                    $("#Qty").val(qualifiedQty);
                    $("#unQty").val(unqualifiedQty);
                    //$("#allowedReceiveQty").val(allowedReceiveQty);
                    $("#status").val(status);
                    $("#remark").val(mrlRemark);
                    $("#qualchkitem").val(qualchkitem);


                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }
    function doSearchUqcqualchkitem() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUtilComboxList";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                tablename: "qc_bd_chk_item_type",
                column_name: "name",
                column_value: "code",
                condition: " is_delete=0 and ext01 = 'LLJC'",
                un:un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            async: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("qualchkitemType"), html);
            }

        });
    }
    function goSelectqualchkitem() {
        var type = $("#qualchkitemType").val();
        if (type) {
            api.openWin({
                name: 'usmSelectQualchkitem',
                url: 'usmSelectQualchkitem.html',
                pageParam: {
                    code: type,
                    name: "qcmChkBillDeal-LLJY",
                }
            });
        } else {
            api.toast({
                msg: "请先选择缺陷类别！",
                duration: 3000
            });
        }

    }
    //产线选择后回调函数
    function setQualchkitem(id, code, name) {
        qualchkitemGid = id;
        qualchkitemCode = code;
        qualchkitemName = name;
        document.getElementById('qualchkitem').value = name;
    }
    function doSearchStatus() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUtilComboxListLLJY";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                tablename: "md_paraconfig",
                column_name: "paracode",
                column_value: "paraval",
                column_attr1: "attr1",
                condition: " paracls='qcChkBillMrlStatus' and paraval in('2','6','1','5') ",
                un:un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            async: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("status"), html);
            }

        });
    }



    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();
        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            if (ret.list) {
                                for (var i = 0; i < ret.list.length; i++) {
                                    var selectImg = ret.list[i];
                                    // 获取图片的路径
                                    var selectimgPath = selectImg.path;
                                    var selectimgThumbPath = selectImg.thumbPath;
                                    // 图片压缩
                                    imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                        var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                            "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                        // 追加图片
                                        $("#addpic").before(showImgHtml);
                                        // ########################################  绑定长按事件 ########################
                                        addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                        // ################### 上传图片 #########################
                                        uploadFile(compressImg);
                                    });
                                }
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }


    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>